<template>
  <div class="project-editor-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button @click="handleBack" icon="el-icon-arrow-left" size="small">
          返回列表
        </el-button>
        <el-divider direction="vertical" />
        <el-button 
          @click="previewMode = !previewMode" 
          :type="previewMode ? 'primary' : 'default'" 
          size="small"
        >
          {{ previewMode ? '退出预览' : '预览' }}
        </el-button>
        <el-button @click="handleSave" icon="el-icon-document" size="small">
          保存
        </el-button>
      </div>
      <div class="toolbar-center">
        <span class="project-title">{{ projectDetail?.title || '项目编辑器' }}</span>
      </div>
      <!-- <div class="toolbar-right">
        <el-button @click="handleExport" icon="el-icon-download" size="small">
          导出
        </el-button>
      </div> -->
    </div>

    <!-- 顶部组件库 -->
    <div class="component-toolbar" v-if="!previewMode">
      <ComponentPanel 
        :horizontal="true"
        @add-component="handleAddComponent" 
      />
    </div>

    <!-- 主要内容区 -->
    <div class="main-content" v-if="!previewMode">
      <!-- 左侧页面列表 -->
      <div class="left-panel">
        <div class="page-panel">
          <div class="page-panel-header">
            <span class="panel-title">页面列表</span>
            <el-button @click="handleAddPage" icon="el-icon-plus" size="mini" type="primary">
              新增页面
            </el-button>
          </div>
          
          <div 
            ref="pageListRef"
            class="page-list"
          >
            <div 
              v-for="(page, index) in pageList" 
              :key="page.id"
              :class="['page-item', { active: currentPageIndex === index }]"
              :data-id="page.id"
              @click="handlePageSelect(index)"
            >
              <div class="page-thumbnail">
                <div class="page-preview">
                  <div class="page-number">{{ index + 1 }}</div>
                  <div class="page-content">
                    <div 
                      v-for="component in page.components.slice(0, 3)" 
                      :key="component.id"
                      class="mini-component"
                    ></div>
                  </div>
                </div>
              </div>
              <div class="page-info">
                <div class="page-title" :title="page.name">
                  {{ page.name || `页面 ${index + 1}` }}
                </div>
                <div class="page-actions">
                  <el-button 
                    @click.stop="handleEditPageTitle(index)" 
                    icon="el-icon-edit" 
                    size="mini" 
                    type="text"
                  ></el-button>
                  <el-button 
                    @click.stop="handleDeletePage(index)" 
                    icon="el-icon-delete" 
                    size="mini" 
                    type="text"
                    :disabled="pageList.length <= 1"
                  ></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间画布区域 -->
      <div class="canvas-area">
        <CanvasComponent
          :key="forceUpdate"
          :project-id="projectId"
          :components="currentPageComponentsDirect"
          @component-select="handleComponentSelect"
          @component-update="handleComponentUpdate"
          @component-delete="handleComponentDelete"
          @component-add="handleComponentAdd"
        />
      </div>

      <!-- 右侧属性面板 -->
      <div class="right-panel">
        <PropertyPanel
          :selected-component="selectedComponent"
          @property-change="handlePropertyChange"
        />
      </div>
    </div>

    <!-- 预览模式 -->
    <div class="preview-content" v-else>
      <PreviewMode
        :project-detail="projectDetail"
        @exit-preview="previewMode = false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { Message, MessageBox } from 'element-ui'
// 使用Element UI的图标，无需导入
// @ts-ignore
import Sortable from 'sortablejs'
import { getProjectDetail } from '@/api/screen-management/report-platform'
import ComponentPanel from './ComponentPanel.vue'
import CanvasComponent from './CanvasComponent.vue'
import PropertyPanel from './PropertyPanel.vue'
import PreviewMode from './PreviewMode.vue'
import type { ProjectDetail, ComponentConfig } from '../interface'



// Props
interface Props {
  projectId: string
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  back: []
  save: []
}>()

// 响应式数据
const previewMode = ref(false)
const projectDetail = ref<ProjectDetail | null>(null)
const selectedComponent = ref<ComponentConfig | null>(null)
const currentPageIndex = ref(0)
const pageListRef = ref<HTMLElement | null>(null)

// 页面列表
const pageList = computed({
  get: () => {
    if (!projectDetail.value?.content?.pages) return []
    return projectDetail.value.content.pages
  },
  set: (newPages) => {
    if (projectDetail.value?.content?.pages) {
      projectDetail.value.content.pages = newPages
    }
  }
})

// 计算属性
const currentPageComponents = computed(() => {
  if (!projectDetail.value?.content?.pages) return []
  const currentPage = projectDetail.value.content.pages[currentPageIndex.value]
  // 强制创建新的数组引用来确保响应式更新
  return currentPage?.components ? [...currentPage.components] : []
})

// 直接管理当前页面组件的响应式数组
const currentPageComponentsDirect = ref<ComponentConfig[]>([])

// 强制更新触发器
const forceUpdate = ref(0)

// 获取项目详情
const loadProjectDetail = async () => {
  try {
    const res = await getProjectDetail(props.projectId)
    if (res.success) {
      projectDetail.value = res.data
      
      // 确保content和pages结构存在
      if (projectDetail.value && !projectDetail.value.content) {
        projectDetail.value.content = {
          pages: [],
          settings: {
            theme: 'default',
            layout: 'default',
            background: '#ffffff'
          }
        }
      }
      if (projectDetail.value && !projectDetail.value.content.pages) {
        projectDetail.value.content.pages = []
      }
      
      // 如果没有页面，创建一个默认页面
      if (projectDetail.value && projectDetail.value.content.pages.length === 0) {
        projectDetail.value.content.pages.push({
          id: 'page_default',
          name: '页面 1',
          components: []
        })
      }
      
      console.log('Project detail loaded:', projectDetail.value)
    } else {
      Message.error(res.message || '获取项目详情失败')
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    Message.error('获取项目详情失败')
  }
}

// 处理返回
const handleBack = () => {
  // emit('back')
}

// 处理保存
const handleSave = async () => {
  
}

// 处理导出
const handleExport = () => {
  // TODO: 实现导出功能
  Message.info('导出功能开发中...')
}

// 处理拖放添加组件
const handleComponentAdd = (componentType: string, position: { x: number, y: number }) => {
  console.log('=== handleComponentAdd called ===')
  console.log('componentType:', componentType)
  console.log('position:', position)
  console.log('projectDetail.value:', projectDetail.value)
  console.log('currentPageIndex.value:', currentPageIndex.value)
  
  if (!projectDetail.value?.content?.pages) {
    console.error('Cannot add component: projectDetail.value.content.pages is not available')
    Message.error('无法添加组件，项目数据未正确加载')
    return
  }
  
  const newComponent: ComponentConfig = {
    id: `component_${Date.now()}`,
    type: componentType,
    name: `${componentType}_${Date.now()}`,
    props: {},
    style: {},
    position: {
      x: position.x,
      y: position.y,
      width: 200,
      height: 100,
    },
  }
  
  console.log('Creating new component:', newComponent)
  
  const currentPage = projectDetail.value.content.pages[currentPageIndex.value]
  if (currentPage) {
    // 使用响应式方法添加组件，确保Vue能够检测到变化
    currentPage.components = [...currentPage.components, newComponent]
    
    // 同时更新直接管理的组件数组
    currentPageComponentsDirect.value = [...currentPage.components]
    
    console.log('Component added to page. Total components:', currentPage.components.length)
    console.log('Current page components:', currentPage.components)
    console.log('Current page index:', currentPageIndex.value)
    console.log('All pages:', projectDetail.value.content.pages)
    console.log('Direct components array updated:', currentPageComponentsDirect.value)
    Message.success(`已添加${componentType}组件`)
    
    // 强制触发响应式更新
    nextTick(() => {
      console.log('NextTick: forcing reactive update')
      // 使用强制更新触发器来确保画布重新渲染
      forceUpdate.value++
      console.log('Force update triggered:', forceUpdate.value)
    })
  } else {
    console.error('Current page not found:', currentPageIndex.value)
    Message.error('当前页面不存在，无法添加组件')
  }
}

// 处理添加组件（点击添加）
const handleAddComponent = (componentType: string) => {
  console.log('=== handleAddComponent called ===')
  console.log('componentType:', componentType)
  
  // 使用默认位置添加组件
  handleComponentAdd(componentType, { x: 100, y: 100 })
}

// 处理组件选择
const handleComponentSelect = (component: ComponentConfig | null) => {
  console.log('=== handleComponentSelect called ===')
  console.log('Component to select:', component)
  selectedComponent.value = component
  console.log('selectedComponent.value set to:', selectedComponent.value)
}

// 处理组件更新
const handleComponentUpdate = (componentId: string, updates: Partial<ComponentConfig>) => {
  console.log('=== handleComponentUpdate called ===')
  console.log('Component ID:', componentId)
  console.log('Updates:', updates)
  
  if (!projectDetail.value?.content?.pages) return
  
  const currentPage = projectDetail.value.content.pages[currentPageIndex.value]
  if (currentPage) {
    const componentIndex = currentPage.components.findIndex(c => c.id === componentId)
    if (componentIndex !== -1) {
      console.log('Updating component at index:', componentIndex)
      
      // 处理属性更新
      if (updates.props) {
        Object.assign(currentPage.components[componentIndex].props, updates.props)
      }
      
      // 处理样式更新
      if (updates.style) {
        Object.assign(currentPage.components[componentIndex].style, updates.style)
      }
      
      // 处理位置更新
      if (updates.position) {
        Object.assign(currentPage.components[componentIndex].position, updates.position)
      }
      
      // 强制触发响应式更新
      currentPage.components.splice(componentIndex, 1, currentPage.components[componentIndex])
      
      // 同步更新直接管理的组件数组
      currentPageComponentsDirect.value = [...currentPage.components]
      
      console.log('Component updated in page data')
      console.log('Updated component:', currentPage.components[componentIndex])
      console.log('currentPageComponentsDirect updated:', currentPageComponentsDirect.value)
    }
  }
}

// 处理组件删除
const handleComponentDelete = (componentId: string) => {
  console.log('=== handleComponentDelete called ===')
  console.log('Component ID to delete:', componentId)
  
  if (!projectDetail.value?.content?.pages) return
  
  const currentPage = projectDetail.value.content.pages[currentPageIndex.value]
  if (currentPage) {
    const componentIndex = currentPage.components.findIndex(c => c.id === componentId)
    if (componentIndex !== -1) {
      console.log('Deleting component at index:', componentIndex)
      currentPage.components.splice(componentIndex, 1)
      
      // 同步更新直接管理的组件数组
      currentPageComponentsDirect.value = [...currentPage.components]
      
      if (selectedComponent.value?.id === componentId) {
        selectedComponent.value = null
      }
      
      console.log('Component deleted, total components:', currentPage.components.length)
      console.log('currentPageComponentsDirect updated:', currentPageComponentsDirect.value)
    }
  }
}

// 处理属性变化
const handlePropertyChange = (property: string, value: any) => {
  console.log('=== handlePropertyChange called ===')
  console.log('Property:', property)
  console.log('Value:', value)
  console.log('Selected component:', selectedComponent.value)
  
  if (!selectedComponent.value) return
  
  // 更新选中组件的属性
  if (property.startsWith('style.')) {
    const styleProp = property.replace('style.', '')
    selectedComponent.value.style[styleProp] = value
    console.log(`Updated style.${styleProp} to:`, value)
  } else if (property.startsWith('props.')) {
    const propName = property.replace('props.', '')
    selectedComponent.value.props[propName] = value
    console.log(`Updated props.${propName} to:`, value)
  } else {
    (selectedComponent.value as any)[property] = value
    console.log(`Updated ${property} to:`, value)
  }
  
  // 同步更新到当前页面的组件数据
  if (projectDetail.value?.content?.pages) {
    const currentPage = projectDetail.value.content.pages[currentPageIndex.value]
    if (currentPage) {
      const componentIndex = currentPage.components.findIndex(c => c.id === selectedComponent.value?.id)
      if (componentIndex !== -1) {
        // 直接更新组件数据，确保响应式
        const targetComponent = currentPage.components[componentIndex]
        
        if (property.startsWith('style.')) {
          const styleProp = property.replace('style.', '')
          targetComponent.style[styleProp] = value
        } else if (property.startsWith('props.')) {
          const propName = property.replace('props.', '')
          targetComponent.props[propName] = value
        } else {
          (targetComponent as any)[property] = value
        }
        
        // 强制触发响应式更新
        currentPage.components.splice(componentIndex, 1, targetComponent)
        
        // 同步更新直接管理的组件数组
        currentPageComponentsDirect.value = [...currentPage.components]
        
        // 强制触发画布重新渲染
        forceUpdate.value++
        
        console.log('Component updated in page data')
        console.log('Updated component:', targetComponent)
        console.log('Force update triggered:', forceUpdate.value)
      }
    }
  }
}

// 页面管理相关方法
const handleAddPage = () => {
  console.log('=== handleAddPage called ===')
  console.log('projectDetail.value:', projectDetail.value)
  
  if (!projectDetail.value?.content?.pages) {
    console.error('Cannot add page: projectDetail.value.content.pages is not available')
    Message.error('无法添加页面，项目数据未正确加载')
    return
  }
  
  const newPage = {
    id: `page_${Date.now()}`,
    name: `页面 ${projectDetail.value.content.pages.length + 1}`,
    components: []
  }
  
  console.log('Adding new page:', newPage)
  projectDetail.value.content.pages.push(newPage)
  currentPageIndex.value = projectDetail.value.content.pages.length - 1
  console.log('Page added, total pages:', projectDetail.value.content.pages.length)
  console.log('Current page index:', currentPageIndex.value)
}

const handlePageSelect = (index: number) => {
  currentPageIndex.value = index
  selectedComponent.value = null
  
  // 同步直接管理的组件数组
  if (projectDetail.value?.content?.pages) {
    const currentPage = projectDetail.value.content.pages[index]
    currentPageComponentsDirect.value = currentPage?.components ? [...currentPage.components] : []
    console.log('Page selected, components synced:', currentPageComponentsDirect.value)
  }
}

const handleEditPageTitle = async (index: number) => {
  if (!projectDetail.value?.content?.pages) return
  
  const page = projectDetail.value.content.pages[index]
  try {
    const result: any = await MessageBox.prompt('请输入页面标题', '编辑页面标题', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: page.name || `页面 ${index + 1}`,
      inputValidator: (value: string) => {
        if (!value || !value.trim()) {
          return '页面标题不能为空'
        }
        return true
      }
    })
    
    page.name = result.value.trim()
  } catch (error) {
    // 用户取消操作
  }
}

const handleDeletePage = async (index: number) => {
  if (!projectDetail.value?.content?.pages || projectDetail.value.content.pages.length <= 1) {
    Message.warning('至少需要保留一个页面')
    return
  }
  
  try {
    await MessageBox.confirm('确定删除此页面吗？删除后无法恢复。', '删除页面', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    projectDetail.value.content.pages.splice(index, 1)
    
    // 调整当前页面索引
    if (currentPageIndex.value >= projectDetail.value.content.pages.length) {
      currentPageIndex.value = projectDetail.value.content.pages.length - 1
    }
    
    selectedComponent.value = null
    Message.success('页面删除成功')
  } catch (error) {
    // 用户取消操作
  }
}

// 初始化Sortable
const initSortable = () => {
  if (!pageListRef.value) return
  
  Sortable.create(pageListRef.value, {
    animation: 200,
    ghostClass: 'sortable-ghost',
    chosenClass: 'sortable-chosen',
    dragClass: 'sortable-drag',
    onEnd: (evt: any) => {
      if (!projectDetail.value?.content?.pages) return
      
      const { oldIndex, newIndex } = evt
      if (oldIndex !== undefined && newIndex !== undefined && oldIndex !== newIndex) {
        const pages = projectDetail.value.content.pages
        const movedPage = pages.splice(oldIndex, 1)[0]
        pages.splice(newIndex, 0, movedPage)
        
        // 更新当前页面索引
        if (currentPageIndex.value === oldIndex) {
          currentPageIndex.value = newIndex
        } else if (currentPageIndex.value > oldIndex && currentPageIndex.value <= newIndex) {
          currentPageIndex.value--
        } else if (currentPageIndex.value < oldIndex && currentPageIndex.value >= newIndex) {
          currentPageIndex.value++
        }
      }
    }
  })
}

// 监听项目ID变化
watch(() => props.projectId, (newId) => {
  if (newId) {
    loadProjectDetail()
  }
}, { immediate: true })

// 组件挂载
onMounted(() => {
  if (props.projectId) {
    loadProjectDetail()
  }
  
  // 初始化拖拽功能
  nextTick(() => {
    initSortable()
  })
})
</script>

<style lang="scss" scoped>
.project-editor-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.toolbar {
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;

  .toolbar-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .toolbar-center {
    flex: 1;
    text-align: center;

    .project-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.component-toolbar {
  height: 80px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  overflow-x: auto;
  overflow-y: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 90;
}

.main-content {
  flex: 1;
  display: flex;
  height: calc(100vh - 130px); // 50px (toolbar) + 80px (component-toolbar)
}

.left-panel {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #e0e0e0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.page-panel {
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-panel-header {
    padding: 16px 12px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .panel-title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
  }
}

.page-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.page-item {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  overflow: hidden;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  }

  &.active {
    border-color: #409eff;
    background-color: #f0f9ff;
  }

  .page-thumbnail {
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;
  }

  .page-preview {
    width: 100%;
    height: 80px;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    position: relative;
    overflow: hidden;

    .page-number {
      position: absolute;
      top: 4px;
      left: 4px;
      background-color: #409eff;
      color: white;
      font-size: 10px;
      padding: 2px 4px;
      border-radius: 2px;
      font-weight: 500;
    }

    .page-content {
      padding: 20px 8px 8px 8px;
      display: flex;
      flex-wrap: wrap;
      gap: 2px;
    }

    .mini-component {
      width: 16px;
      height: 8px;
      background-color: #c6d5f7;
      border-radius: 1px;
    }
  }

  .page-info {
    padding: 8px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 12px;
      color: #606266;
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-right: 8px;
    }

    .page-actions {
      display: flex;
      gap: 4px;
      opacity: 0;
      transition: opacity 0.2s ease;

      .el-button {
        padding: 4px;
        min-height: auto;
        color: #909399;

        &:hover {
          color: #409eff;
        }
      }
    }
  }

  &:hover .page-actions {
    opacity: 1;
  }
}

.canvas-area {
  flex: 1;
  background-color: #f8f9fa;
  overflow: auto;
}

.right-panel {
  width: 300px;
  background-color: #fff;
  border-left: 1px solid #e0e0e0;
  overflow-y: auto;
}

.preview-content {
  flex: 1;
  width: 100%;
  height: calc(100vh - 50px);
}

// 滚动条样式
.page-list::-webkit-scrollbar {
  width: 4px;
}

.page-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.page-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.page-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

// 拖拽样式
.sortable-ghost {
  opacity: 0.5;
}

.sortable-chosen {
  transform: scale(1.02);
}

.sortable-drag {
  transform: rotate(2deg);
}
</style>
